﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;

namespace Xant.FlowEngine
{
    public static class DBConnectionManager
    {
        private static string connectionName = "XantFlow";
        public static ProviderType ProviderType { get; private set; }
        public static string ConnectionString { get; private set; }

        static DBConnectionManager()
        {
            var connConfig = ConfigurationManager.ConnectionStrings[connectionName];
            if (connConfig == null)
            {
                throw new ApplicationException("未在程序的config文件中配置数据库连接。");
            }
            ProviderType = ProviderType.SqlServer;//如果未指定连接提供都名称，则默认为SQL SERVER
            if (!string.IsNullOrEmpty(connConfig.ProviderName))
            {
                if ("System.Data.SqlClient".Equals(connConfig.ProviderName, StringComparison.CurrentCultureIgnoreCase))
                {
                    ProviderType = ProviderType.SqlServer;
                }
                else if ("MySql.Data.MySqlClient".Equals(connConfig.ProviderName, StringComparison.CurrentCultureIgnoreCase))
                {
                    ProviderType = ProviderType.MySql;
                }
            }
            ConnectionString = connConfig.ConnectionString;
        }

        public static IDbConnection GetConnection()
        {
            IDbConnection conn = null;
            switch (ProviderType)
            {
                case ProviderType.SqlServer:
                    conn = new SqlConnection(ConnectionString);
                    break;
                case ProviderType.MySql:
                    conn = new MySqlConnection(ConnectionString);
                    break;
            }
            return conn;
        }

    }

    public enum ProviderType
    {
        SqlServer,
        MySql,
        /*Oracle,
        OleDb,
        Odbc,*/
    }

}
